package com.opener.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author baboy
 * @date 06/11/2017
 */
public class JsonUtils{

    public static Object parse(String s, Class valueType){
        ObjectMapper mapper = new ObjectMapper();
        Object obj = null;
        try {
            obj = mapper.readValue(s, valueType);
        }catch (Exception e){
            e.printStackTrace();
        }
        return obj;
    }
    public  static Object parse(String s){
        Object obj = null;
        String ARR_START_CHAR = "[";
        String MAP_START_CHAR = "{";

        if(s.startsWith(ARR_START_CHAR)){
            obj = parse(s, ArrayList.class);
        }else if(s.startsWith(MAP_START_CHAR)){
            obj = parse(s, HashMap.class);
        }
        return obj;
    }
    public static String toString(Object obj, boolean indent){
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(SerializationFeature.INDENT_OUTPUT, indent);
        mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
        String s = null;
        try {
            s = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }
    public static String toString(Object obj){
        return toString(obj, true);
    }
}
